//
//  MinePublishViewController.m
//  Find
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "MinePublishViewController.h"
#import "MinePublishCell.h"
#import "LostDetailViewController.h"
#define kCollectFind @"collectFind"
#define kCollectLost @"collectLost"
#define kPublishFind @"publishFind"
#define kPublishLost @"publishLost"

@interface MinePublishViewController ()<UITableViewDataSource, UITableViewDelegate>



@end

@implementation MinePublishViewController
- (instancetype)init
{
    if (self = [super init]) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return  self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.minePublishArray = [NSMutableArray array];
    if (self.minePublishCollec) {
        
        [self setUpData1];
    } else {
        [self setUpData2];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    // 调用 添加界面内容
    [self addSubViews];
    // 查询文件路径  数据库文件
//    NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject);
}




#pragma mark  -- 添加页面内容
- (void)addSubViews
{
#pragma mark -- 创建子线程请求数据 并刷新tableview
    
    // 设置navigationBar 背景颜色 用图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iconfont-navbar-back"] forBarMetrics:UIBarMetricsDefault];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Returns"] style:UIBarButtonItemStylePlain target:self action:@selector(actionBackButton:)];
    backButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backButton;
#pragma  mark -- tableview
    self.minePublishTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:(UITableViewStylePlain)];
    // 设置导航条不透明
//    self.navigationController.navigationBar.translucent = NO;
    self.minePublishTableView.delegate = self;
    self.minePublishTableView.dataSource = self;
    [self.minePublishTableView registerNib:[UINib nibWithNibName:@"MinePublishCell" bundle:nil] forCellReuseIdentifier:@"MinePublishCell"];
    [self.view addSubview:self.minePublishTableView];
    
    
    
#pragma  mark -- 右上角管理编辑状态
    UIBarButtonItem * minePublishRightBar = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:(UIBarButtonItemStyleDone) target:self action:@selector(minePublishRIghtAction:)];
    minePublishRightBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = minePublishRightBar;
    
}
- (void)actionBackButton:(UIBarButtonItem *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setUpData1
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 60)];
    label.text = @"我的收藏";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Helvetica" size:18];
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
#pragma mark --- 我的收藏的数据 的获取
    AVUser *user = [AVUser currentUser];
    AVRelation *collectFind = [user relationforKey:kCollectFind];
    [[collectFind query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (FindMessageModel *model in objects) {
                [self.minePublishArray addObject:model];
            }
        } else {
       
        }
        // 回调主线程刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.minePublishTableView reloadData];
        });
        
    }];
    
    AVRelation *collectLost = [user relationforKey:kCollectLost];
    [[collectLost query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (LostMessageModel *model in objects) {
                [self.minePublishArray addObject:model];
            }
        } else {
     
        }
        // 回调主线程刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.minePublishTableView reloadData];
        });
    }];
    
    
}
#pragma mark -- 我的发布的数据获取
- (void)setUpData2
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 60)];
    label.text = @"我的发布";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Helvetica" size:18];
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    AVUser *user = [AVUser currentUser];
    AVRelation *publishFind = [user relationforKey:kPublishFind];
    [[publishFind query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (FindMessageModel *model in objects) {
               
                [self.minePublishArray addObject:model];
                
            }
            
        } else {
    
        }
        // 回调主线程刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.minePublishTableView reloadData];
        });
        
    }];
   
    
    AVRelation *publishLost = [user relationforKey:kPublishLost];
    [[publishLost query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (LostMessageModel *model in objects) {
                [self.minePublishArray addObject:model];
            }
        } else {
            
        }
        // 回调主线程刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.minePublishTableView reloadData];
        });
    }];
    
    
    }

#pragma mark -- 实现右上角按钮编辑
- (void)minePublishRIghtAction:(UIBarButtonItem *)rightBar
{
    // 开启编辑状态
    [self.minePublishTableView setEditing:!self.minePublishTableView.editing animated:YES];
    // 更改编辑按钮
    if (self.minePublishTableView.editing == YES) {
        rightBar.title = @"完成";
    } else {
        rightBar.title = @"编辑";
    }
}

#pragma mark -- 实现tableview代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.minePublishArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MinePublishCell * Listcell = [tableView dequeueReusableCellWithIdentifier:@"MinePublishCell" forIndexPath:indexPath];
    Listcell.backgroundColor = [UIColor whiteColor];
#pragma mark-- 收藏 数据赋值
#pragma mark --- 发布数据赋值
        AVObject *object = self.minePublishArray[indexPath.row];
        Listcell.titleLabel.text = [object valueForKey:@"title"];
        Listcell.contextLabel.text = [object valueForKey:@"context"];
    
    
    UIView *select = [[UIView alloc] init];
    select.backgroundColor = [UIColor clearColor];
    Listcell.selectedBackgroundView = select;
    return Listcell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.minePublishCollec) {
        return YES;
    } else {
        self.navigationItem.rightBarButtonItem = nil;
        return NO;
        
    }
}


// 返回每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

#pragma mark --  删除数据
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        // 首先判断是我的收藏还是我的发布界面
        // 先删除云服务器数据
        // 我的发布页面
        if (self.minePublishCollec) {
     
         AVUser *user = [AVUser currentUser];
         AVObject *object = self.minePublishArray[indexPath.row];
            if ([[object class] isSubclassOfClass:[FindMessageModel class]]) {
                AVRelation *relation = [user relationforKey:@"collectFind"];
                [relation removeObject:object];
                [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                    
                    }
                }];

        } else {
            AVRelation *relation = [user relationforKey:@"collectLost"];
            [relation removeObject:object];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
               
                }
            }];
        }
        
        // 删除数组中数据
        [self.minePublishArray removeObjectAtIndex:indexPath.row];
        // 删除界面中数据
            
        [self.minePublishTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
    } else {
       
    }
    } else {
        self.navigationItem.rightBarButtonItem = nil;
        self.minePublishTableView.editing = NO;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"不再收藏";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     AVObject *object = self.minePublishArray[indexPath.row];
    if (self.minePublishCollec) {
      // find
        if ([[object class]isEqual:[FindMessageModel class]]) {
            FindDetailViewController *findDetailVC = [[FindDetailViewController alloc] init];
            findDetailVC.objectID = object.objectId;
             [self.navigationController pushViewController:findDetailVC animated:YES];
        } else {
            LostDetailViewController   *lostDetailVC = [[LostDetailViewController alloc] init];
            lostDetailVC.objectID = object.objectId;
            [self.navigationController pushViewController:lostDetailVC animated:YES];
        }

        
    } else {
        if ([[object class]isEqual:[FindMessageModel class]]) {
            FindDetailViewController *findDetailVC = [[FindDetailViewController alloc] init];
            findDetailVC.objectID = object.objectId;
            [self.navigationController pushViewController:findDetailVC animated:YES];
        } else {
            LostDetailViewController   *lostDetailVC = [[LostDetailViewController alloc] init];
            lostDetailVC.objectID = object.objectId;
            [self.navigationController pushViewController:lostDetailVC animated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
